package org.example.servlet;

import org.example.entity.User;
import org.example.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

/**
 * 服务器显示添加用户
 */
@WebServlet("/useradd")
public class UserAddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8"); //防止中文乱码
        //添加用户，接受用户输入的信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        System.out.println("获取请求参数："+username+password+phone);
        //创建用户并封装属性
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setRole(1); //1表示普通用户
        user.setCreateTime(LocalDateTime.now()); //当前系统时间
        //调用业务方法
        UserServiceImpl userService = new UserServiceImpl();
        int i = userService.addUser(user);
        //返回相应信息
        System.out.println(i>0?"添加用户成功":"添加用户失败");
        String msg = "";
        if (i>0){
          msg+="恭喜"+user.getUsername()+"添加成功";
        }else {
            msg+="抱歉"+user.getUsername()+"添加失败";
        }
        //响应数据
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.write(msg);
        out.flush();
        out.close();
    }
}
